import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/models/home_bill_details_meter_fee_entity.dart';
import 'package:kkhousekeep/models/home_bill_details_once_fee_entity.dart';
import 'package:kkhousekeep/models/home_bill_details_repeat_fee_entity.dart';
import 'package:kkhousekeep/page/home/convenient/bill/bill_details_controller.dart';
import 'package:kkhousekeep/widget/custom_app_bar.dart';

import '../../../../models/home_bill_details_entity.dart';
import '../../../../widget/marquee.dart';

class BillDetailsPage extends StatelessWidget {
  const BillDetailsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage("assets/images/page_bg.png"),
              fit: BoxFit.fill)),
      child: GetBuilder(
        init: BillDetailsController(),
        builder: (controller) => Scaffold(
          backgroundColor: Colors.transparent,
          appBar: CustomAppBar(
            "${controller.year}年${controller.month}月账单",
            backgroundColor: Colors.transparent,
          ),
          body: Stack(
            alignment: AlignmentDirectional.topCenter,
            children: [
              _buildDetailsItemList(controller),
              _buildIconWidget(controller),
            ],
          ),
        ),
      ),
    );
  }

  ///顶部widget
  Widget _buildIconWidget(BillDetailsController controller) {
    return Positioned(
        top: 66.h,
        child: Container(
          width: 686.w,
          height: 215.h,
          padding: EdgeInsets.only(top: 28.h),
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/home_bill_underlay.png"),
            ),
          ),
          child: Column(
            children: [
              Obx(() => Text(
                    controller.address.value,
                    style: TextStyle(
                        fontSize: 24.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w400),
                  )),
              Obx(() => Text(
                    '￥${controller.totalMoney.value.toStringAsFixed(2)}',
                    style: TextStyle(
                        fontSize: 48.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w600),
                  )),
              Obx(() => Text(
                    "共有${controller.items.length}项应缴费用项,"
                    "合计${controller.totalMoney.value.toStringAsFixed(2)}元",
                    style: TextStyle(fontSize: 24.sp, color: Colors.white),
                  ))
            ],
          ),
        ));
  }

  ///中部列表
  Widget _buildDetailsItemList(BillDetailsController controller) {
    return Positioned(
        top: 238.h,
        child: Container(
          height: 1236.h,
          width: 1.sw,
          padding: EdgeInsets.only(top: 86.h),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topRight: Radius.circular(48.w),
                  topLeft: Radius.circular(48.w))),
          child: SizedBox(
            width: 1.sw,
            height: 1068.h,
            child: Obx(() => ListView.builder(
                itemCount: controller.items.length,
                itemBuilder: (context, index) =>
                    _buildExpansionTileItem(controller.items[index], context))),
          ),
        ));
  }

  ///展开列表
  Widget _buildExpansionTileItem(
      HomeBillDetailsObjItems item, BuildContext context) {
    //根据textPainter的宽度决定是否使用跑马灯
    var itemNameTextPainter = TextPainter(
      textDirection: TextDirection.rtl,
      text: TextSpan(
        text: item.itemName,
        style: TextStyle(
          fontSize: 32.sp,
          color: const Color(0xFF6D6D6D),
        ),
      ),
    );
    itemNameTextPainter.layout();

    //隐藏ExpansionTile展开时的划线
    return Theme(
      data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
      child: ExpansionTile(
        tilePadding: EdgeInsets.only(
          right: 65.w,
          top: 16.h,
          bottom: 16.h,
        ),
        title: Container(
          padding: EdgeInsets.only(left: 72.w),
          child: Flex(
            direction: Axis.horizontal,
            children: [
              Expanded(
                  flex: 70,
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          height: 40.h,
                          child: itemNameTextPainter.width > 250.w
                              ? MarqueeContinuous(_buildBillNameWidget(item))
                              : _buildBillNameWidget(item),
                        ),
                        SizedBox(
                          height: 12.w,
                        ),
                        Text(
                          "${item.startDate}~${item.endDate}",
                          style: TextStyle(
                              fontSize: 24.sp, color: const Color(0xFF999999)),
                        )
                      ],
                    ),
                  )),
              Expanded(
                  flex: 30,
                  child: Container(
                    alignment: Alignment.centerRight,
                    child: Text(
                      '${_getItemSumMoney(item).toStringAsFixed(2)}元',
                      style: TextStyle(
                        fontSize: 32.sp,
                        fontWeight: FontWeight.bold,
                        color: const Color(0xFF6D6D6D),
                      ),
                    ),
                  ))
            ],
          ),
        ),
        children: _buildExpansionChild(item),
      ),
    );
  }

  //展开列表各项的展开项
  List<Widget> _buildExpansionChild(HomeBillDetailsObjItems item) {
    //非一次性收费
    FeeType feeType = FeeType.getFeeTypeById(item.feeItemProperty);
    String leftContent = _getLeftContent(item, feeType);
    String rightContent = _getRightContent(item, feeType);

    String firstLeftContent = _getLeftContent(item, feeType, isFirst: true);
    String firstRightContent = _getRightContent(item, feeType, isFirst: true);
    return [
      _buildExtendOneRowItem(firstLeftContent, firstRightContent),
      _buildExtendOneRowItem(leftContent, rightContent),
    ];
  }

  Widget _buildExtendOneRowItem(String leftContent, String rightContent) {
    return Container(
      height: 72.h,
      margin: EdgeInsets.only(left: 32.w, right: 32.w),
      color: const Color(0xFFF0F2F7),
      padding: EdgeInsets.only(left: 40.w, right: 40.w),
      child: Flex(
        direction: Axis.horizontal,
        children: [
          Expanded(
              flex: 70,
              child: Container(
                alignment: Alignment.centerLeft,
                child: Text(
                  leftContent,
                  style: TextStyle(
                      fontSize: 28.sp, color: const Color(0xFF999999)),
                ),
              )),
          Expanded(
              flex: 30,
              child: Container(
                alignment: Alignment.centerRight,
                child: Text(
                  '$rightContent元',
                  style: TextStyle(
                      fontSize: 28.sp, color: const Color(0xFF999999)),
                ),
              ))
        ],
      ),
    );
  }

  Widget _buildBillStateWidget(BillState state) {
    String content = state.name;
    Color color = Color(state.color);
    return Container(
      width: 108.w,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(8.w),
          ),
          border: Border.all(color: color)),
      child: Text(
        content,
        style: TextStyle(
          fontSize: 28.sp,
          color: color,
        ),
      ),
    );
  }

  Widget _buildBillNameWidget(HomeBillDetailsObjItems item) {
    return Row(
      children: [
        Text(
          item.itemName,
          style: TextStyle(fontSize: 32.sp, color: const Color(0xFF6D6D6D)),
        ),
        SizedBox(
          width: 18.w,
        ),
        _buildBillStateWidget(BillState.getBillStateById(item.state)),
      ],
    );
  }

  double _getItemSumMoney(HomeBillDetailsObjItems item) {
    FeeType feeType = FeeType.getFeeTypeById(item.feeItemProperty);

    if (FeeType.meterFee == feeType) {
      var meterFeeEntity =
          HomeBillDetailsMeterFeeEntity.fromJson(jsonDecode(item.detail));
      return item.damages + meterFeeEntity.itemCost;
    }

    if (FeeType.repeatFee == feeType) {
      var repeatFeeEntity =
          HomeBillDetailsRepeatFeeEntity.fromJson(jsonDecode(item.detail));
      return item.damages + repeatFeeEntity.itemCost;
    }

    if (FeeType.onceFee == feeType) {
      var onceFeeEntity =
          HomeBillDetailsOnceFeeEntity.fromJson(jsonDecode(item.detail));
      return item.damages + onceFeeEntity.itemCost;
    }
    return 0.0;
  }

  String _getLeftContent(
    HomeBillDetailsObjItems item,
    FeeType feeType, {
    bool isFirst = false,
  }) {
    if (FeeType.meterFee == feeType) {
      if (isFirst) {
        var meterFeeEntity =
            HomeBillDetailsMeterFeeEntity.fromJson(jsonDecode(item.detail));
        var startDosage = meterFeeEntity.startDosage.toStringAsFixed(1);
        var endDosage = meterFeeEntity.endDosage.toStringAsFixed(1);
        var unit = meterFeeEntity.unit;
        var dosage = (meterFeeEntity.endDosage - meterFeeEntity.startDosage)
            .toStringAsFixed(1);
        return '$startDosage$unit - $endDosage$unit 用量$dosage$unit';
      }
      return '违约金';
    }
    if (FeeType.repeatFee == feeType || FeeType.onceFee == feeType) {
      if (isFirst) {
        return item.itemName;
      }
      return '违约金';
    }

    return '';
  }

  String _getRightContent(
    HomeBillDetailsObjItems item,
    FeeType feeType, {
    bool isFirst = false,
  }) {
    if (FeeType.meterFee == feeType) {
      if (isFirst) {
        var meterFeeEntity =
            HomeBillDetailsMeterFeeEntity.fromJson(jsonDecode(item.detail));
        return meterFeeEntity.itemCost.toStringAsFixed(2);
      }
      return item.damages.toStringAsFixed(2);
    }

    if (FeeType.onceFee == feeType) {
      if (isFirst) {
        var onceFeeEntity =
            HomeBillDetailsOnceFeeEntity.fromJson(jsonDecode(item.detail));
        return onceFeeEntity.itemCost.toStringAsFixed(2);
      }
      return item.damages.toStringAsFixed(2);
    }

    if (FeeType.repeatFee == feeType) {
      if (isFirst) {
        var repeatFeeEntity =
            HomeBillDetailsRepeatFeeEntity.fromJson(jsonDecode(item.detail));
        return repeatFeeEntity.itemCost.toStringAsFixed(2);
      }
      return item.damages.toStringAsFixed(2);
    }

    return '';
  }
}
